package com.sangjie.souyidai.https;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.commons.lang.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.ByteArrayBuffer;

public class Souyidai {

	private static final String ZONE_ID = "Asia/Shanghai";
//	private static final String ZONE_ID = "Pacific/Wallis";
	
    private static boolean bided = false;
    private static SouyidaiTherad souyidai;
    private static Timer timer;

    public Souyidai() {
    	bided = false;
    }
    /**
     * @param args
     * @throws HttpException
     * @throws IOException
     * @throws NoSuchAlgorithmException
     * @throws KeyStoreException
     * @throws KeyManagementException
     * @throws InterruptedException 
     */
    public static void main(String[] args) throws HttpException, IOException, NoSuchAlgorithmException,
            KeyStoreException, KeyManagementException, InterruptedException {
//    	String [] ids = TimeZone.getAvailableIDs();
//    	for(int i=0; i<ids.length; i++) {
//    		System.out.println(ids[i]);
//    	}
//    	Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(ZONE_ID));
//    	System.out.println(cal.get(Calendar.HOUR_OF_DAY));
//    	printTime("", cal);
    	
    	new Souyidai().bid("5628375803863", 1);
    }
    
    public static void signIn() {
    	try {
	    	SSLContextBuilder builder = new SSLContextBuilder();
	        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
	        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
	        ConnectionConfig connectionConfig = ConnectionConfig.custom().setBufferSize(4128).build();
	        final CloseableHttpClient httpclient = HttpClients.custom()
	                .setDefaultConnectionConfig(connectionConfig).setSSLSocketFactory(sslsf).build();
	        
	    	login(httpclient);
	    	sign(httpclient);
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    }
    
    // 登录
    public static CloseableHttpResponse login(CloseableHttpClient httpclient) throws Exception {
    	HttpPost httpPost = new HttpPost("https://passport.souyidai.com/login/jsonLogin");
        List<NameValuePair> logingFormparams = new ArrayList<NameValuePair>();
//        logingFormparams.add(new BasicNameValuePair("username", "13207605260"));
//        logingFormparams.add(new BasicNameValuePair("password", "ccjA140826110649"));
        logingFormparams.add(new BasicNameValuePair("username", "13810114052"));
        logingFormparams.add(new BasicNameValuePair("password", "123qweASD@"));
        logingFormparams.add(new BasicNameValuePair("backurl", "https://www.souyidai.com/"));

        httpPost.setHeader("Connection", "keep-alive");
        httpPost.setHeader("Accept", "application/json, text/javascript, */*; q=0.01");
        httpPost.setHeader("Origin", "https://passport.souyidai.com");
        httpPost.setHeader("X-Requested-With", "XMLHttpRequest");
        httpPost.setHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36");
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        httpPost.setHeader("Referer",
                "https://passport.souyidai.com/?backurl=http://www.souyidai.com/myaccount/capital");
        httpPost.setHeader("Accept-Encoding", "gzip, deflate");
        httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
        
        UrlEncodedFormEntity requestLoginEntity = new UrlEncodedFormEntity(logingFormparams, Consts.UTF_8);
        httpPost.setEntity(requestLoginEntity);
        CloseableHttpResponse response = httpclient.execute(httpPost);
        try {
            HttpEntity entity = response.getEntity();
            InputStream inputStream = entity.getContent();
            ByteArrayBuffer bab = new ByteArrayBuffer(1024);
            int b;
            while ((b = inputStream.read()) != -1) {
                bab.append(b);
            }

            String str = new String(bab.toByteArray(), "utf-8");
            System.out.println(str);
            System.out.println("LOGIN SUCCESS !");
        } finally {
            response.close();
        }
        return response;
    }
    
    // 签到
    public static CloseableHttpResponse sign(CloseableHttpClient httpclient) throws Exception {
    	HttpPost httpPost = new HttpPost("https://www.souyidai.com/profile/sign/signIn");
        List<NameValuePair> logingFormparams = new ArrayList<NameValuePair>();
        logingFormparams.add(new BasicNameValuePair("page", "myacc"));
        logingFormparams.add(new BasicNameValuePair("t", "0.23196517603875777"));

        httpPost.setHeader("Connection", "keep-alive");
        httpPost.setHeader("Accept", "application/json, text/javascript, */*; q=0.01");
        httpPost.setHeader("Origin", "https://passport.souyidai.com");
        httpPost.setHeader("X-Requested-With", "XMLHttpRequest");
        httpPost.setHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36");
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        httpPost.setHeader("Referer",
                "https://www.souyidai.com/myaccount/capital?tomc");
        httpPost.setHeader("Accept-Encoding", "gzip, deflate");
        httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
        httpPost.setHeader("cache-control", "no-cache");
        httpPost.setHeader("x-requested-with", "XMLHttpRequest");
        httpPost.setHeader("pragma", "no-cache");
        httpPost.setHeader("origin", "https://www.souyidai.com");
        
        UrlEncodedFormEntity requestLoginEntity = new UrlEncodedFormEntity(logingFormparams, Consts.UTF_8);
        httpPost.setEntity(requestLoginEntity);
        CloseableHttpResponse response = httpclient.execute(httpPost);
        try {
            HttpEntity entity = response.getEntity();
            InputStream inputStream = entity.getContent();
            ByteArrayBuffer bab = new ByteArrayBuffer(1024);
            int b;
            while ((b = inputStream.read()) != -1) {
                bab.append(b);
            }

            String str = new String(bab.toByteArray(), "utf-8");
            System.out.println(str);
            String result = "\"signStatus\":1";
            if (str != null && str.contains(result)) {
            	System.out.println("SIGN SUCCESS !");
            }
        } finally {
            response.close();
        }
        return response;
    }
    
    public void cancel() {
    	if (timer != null) {
    		timer.cancel();
    	}
    }
    
    public void bid(String bid, final int amount) {
    	if (StringUtils.isBlank(bid) || amount <= 0) {
    		System.out.println("invalid params : bid=" + bid + ", amount=" +  amount);
    		return;
    	}

        System.out.println("bidId : " + bid + ", amount: " + amount);

        souyidai = new Souyidai.SouyidaiTherad(bid, amount);

        timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(ZONE_ID));
                int hour = cal.get(Calendar.HOUR_OF_DAY);
                int minute = cal.get(Calendar.MINUTE);
                int second = cal.get(Calendar.SECOND);
                boolean condition1 = (hour == 10 && minute == 29);
                boolean condition2 = (hour == 14 && minute == 29);
                boolean condition3 = (hour == 19 && minute == 59);

                boolean condition11 = (hour == 10 && minute == 30);
                boolean condition22 = (hour == 14 && minute == 30);
                boolean condition33 = (hour == 20 && minute == 0);
                printTime("current time is : ", cal);

// test code
// if (second >= 5 && second <= 59) {
                if (((condition1 || condition2 || condition3) && second >= 50)) {
                    if (!bided) {
                        new Thread(souyidai).start();
                        bided = true;
                    }
                    System.out.println("bid timer reached");
                } else if ((condition11 || condition22 || condition33) && second >= 1) {
// test code
// } else if (second >= 1 && second <= 2) {
                    timer.cancel();
                    souyidai.setTimeUp();
                    System.out.println("bid completed, see result");
                } else {
                    System.out.println("timer did not reach yet");
                }
            }
        }, 0, 1000);// 设定指定的时间time,此处为1000毫秒
    }
    
    private static void printTime(String prefix, Calendar cal) {
    	System.out.println(prefix + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND) + ":" + cal.get(Calendar.MILLISECOND));
    }

    private static class BidThread implements Runnable {
        CloseableHttpClient httpClient;
        HttpPost httpPost;
        int i;

        public BidThread(CloseableHttpClient httpClient, HttpPost httpPost, int i) {
            this.httpClient = httpClient;
            this.httpPost = httpPost;
            this.i = i;
        }

        public void run() {
            try {
                Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(ZONE_ID));
                printTime("thread " + i + " starts : time is : ", cal);
                CloseableHttpResponse response = httpClient.execute(httpPost);
                try {
                    HttpEntity entity = response.getEntity();
                    InputStream inputStream = entity.getContent();
                    ByteArrayBuffer bab = new ByteArrayBuffer(1024);
                    int b;
                    while ((b = inputStream.read()) != -1) {
                        bab.append(b);
                    }

                    String str = new String(bab.toByteArray(), "utf-8");
                    cal = Calendar.getInstance(TimeZone.getTimeZone(ZONE_ID));
                    printTime("thread " + i + "returns : " + str + ", current time is : ", cal);
//                    if (str != null && (str.contains("\"retCode\":0") || str.contains("\"retCode\":70"))) {
                        System.out.println("BID SUCCESS !!!!!!");
                        timer.cancel();
                        souyidai.setTimeUp();
                        System.out.println("bid completed, see result");
//                    }
                    printTime("thread " + i + " run end, current time is : ", cal);
                    // System.out.println(i + str);
                } finally {
                    response.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    static class SouyidaiTherad implements Runnable {

        String bidId = "";
        int amount = 0;

        boolean timeUp = false;

        public SouyidaiTherad(String bidId, int amount) {
            this.bidId = bidId;
            this.amount = amount;
        }

        public void setTimeUp() {
            timeUp = true;
        }

        @Override
        public void run() {

            try {
                SSLContextBuilder builder = new SSLContextBuilder();
                builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
                ConnectionConfig connectionConfig = ConnectionConfig.custom().setBufferSize(4128).build();
                final CloseableHttpClient httpclient = HttpClients.custom()
                        .setDefaultConnectionConfig(connectionConfig).setSSLSocketFactory(sslsf).build();

                HttpPost httpPost = null;

                // 登录
                login(httpclient);

                // 投标
                httpPost = new HttpPost("https://www.souyidai.com/bid/dobid");

                List<NameValuePair> bidFormparams = new ArrayList<NameValuePair>();
                bidFormparams.add(new BasicNameValuePair("bidId", bidId));
                bidFormparams.add(new BasicNameValuePair("bidAmount", String.valueOf(amount * 100)));
                bidFormparams.add(new BasicNameValuePair("isFullAmountBuy", "true")); // 是否全额投，为true则只投你指定的金额
                bidFormparams.add(new BasicNameValuePair("authCode", ""));
                bidFormparams.add(new BasicNameValuePair("couponUserId", "0"));
                bidFormparams.add(new BasicNameValuePair("isUseCoupon", "1"));
                // 加息卷
                // bidFormparams.add(new
                // BasicNameValuePair("raiseInterestCouponId",
                // "2369688"));

                UrlEncodedFormEntity requestBidEntity = new UrlEncodedFormEntity(bidFormparams, Consts.UTF_8);
                httpPost.setEntity(requestBidEntity);

                httpPost.setHeader("Connection", "keep-alive");
                httpPost.setHeader("Accept", "application/json, text/javascript, */*; q=0.01");
                httpPost.setHeader("Origin", "https://passport.souyidai.com");
                httpPost.setHeader("X-Requested-With", "XMLHttpRequest");
                httpPost.setHeader("User-Agent",
                        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36");
                httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                httpPost.setHeader("Referer", "https://www.souyidai.com/invest");
                httpPost.setHeader("Accept-Encoding", "gzip, deflate");
                httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
                // Cookie:syd_freshman_guide=1; ydt_freshman_guide=1;
                // IPLOC=CN1100;
                // SUV=1410301131065107;
                // tma=227568415.74626275.1453951271451.1453951271451.1453951271451.1;
                // tmd=1.227568415.74626275.1453951271451.;
                // bairong_c_gid=1d8d45843838effba73ddb8d00000152863f1bec;
                // myacc_banner=2016/01/11/1452498594428.jpg;
                // _jsid=f51c141c-650f-4a5d-afb7-d454e7fc5aa1;
                // syd_name=cyoqKioqKmU%3D;
                // syd_auth=1053518%7C%7CcyoqKioqKmU%3D%7C%7C2016%2F01%2F29-10%3A55%7C%7C894f20779dd53c8ba535ba412b9c35f9;
                // JSESSIONID=aaaz0ENMZKkda_S6UnFiv;
                // Hm_lvt_51bfa68f6bea432417d90d76280e520f=1453951261,1454034306,1454036100,1454036145;
                // Hm_lpvt_51bfa68f6bea432417d90d76280e520f=1454037602;
                // _pk_id.1.a855=dc95d1f0d5350c46.1446104660.48.1454037602.1454034310.;
                // _pk_ses.1.a855=*
                // Content-Length:94

                boolean bidStarted = false;
                int k = 0;
                while (!timeUp) {
                	
// test code
//timeUp = true;
                	
                    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(ZONE_ID));
                    int second = cal.get(Calendar.SECOND);

                    if (!bidStarted) {
						if (second >= 59) {
                            bidStarted = true;
                            bid(httpclient, httpPost, k);
                            k++;
						} else {
						    System.out.println("not reached 59");
						    Thread.sleep(300);
						}
                    } else {
                        bid(httpclient, httpPost, k);
                        k++;
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        private void bid(CloseableHttpClient httpClient, HttpPost httpPost, int k) throws Exception {
            System.out.println("seconds reached 59");
            BidThread myThread1 = new BidThread(httpClient, httpPost, k);
            new Thread(myThread1).start();
            Thread.sleep(50);
        }

    }
}
